package com.qf.emp.dao.impl;

import com.qf.emp.dao.IEmpDao;
import com.qf.emp.entity.Emp;
import com.qf.emp.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class EmpDaoImpl implements IEmpDao {
    QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public Integer insert(Emp emp) throws SQLException {
        String sql = "insert into t_emp(ename,sal,comm,hiredate,mgr,deptno,job) values(?,?,?,?,?,?,?)";
        return qr.update(sql, emp.getEname(), emp.getSal(), emp.getComm(), emp.getHiredate(), emp.getMgr(), emp.getDeptno(), emp.getJob());
    }

    @Override
    public Emp selectById(Integer id) throws SQLException {
        String sql = "select * from t_emp where empno = ?";
        Emp emp = qr.query(sql, new BeanHandler<Emp>(Emp.class), id);
        return emp;
    }

    @Override
    public Integer updateById(Emp emp) throws SQLException {
        String sql = "update t_emp set ename = ?,sal = ?,comm = ?,hiredate = ?,mgr = ?,deptno= ?,job = ? where empno = ?";
        return qr.update(sql, emp.getEname(), emp.getSal(), emp.getComm(), emp.getHiredate(), emp.getMgr(), emp.getDeptno(), emp.getJob(), emp.getEmpno());

    }

    @Override
    public Integer deleteById(Integer id) throws SQLException {
        String sql = "delete from t_emp where empno = ?";
        return qr.update(sql, id);

    }

    @Override
    public List<Emp> selectList() throws SQLException {
        String sql = "select * from t_emp";
        return qr.query(sql, new BeanListHandler<Emp>(Emp.class));
    }
}
